package com.example.testdemo.video_progress;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;


/**
 * Created by 颜 on 04.18.018.
 * 仿抖音视频进度条
 */

public class VideoProgressBar extends View {
    private static final String TAG = "VideoProgressBar";
    private long duration;//总时长
    private long progress;//当前进度

    private Paint mPaint;//画笔
    private Paint volumePaint;//音量画笔
    private Paint bufferPaint;//缓冲画笔
    private Rect mRect;//线区域
    private Rect bufferRect;//缓冲区域
    private Rect progressRect;//进度区域
    private Rect volumeRect;//音量区域
    private boolean isBuffer;//是否在缓冲
    private boolean isShowProgress;//是否显示进度（默认不显示）

    private int changePx;//改变大小像素
    private int left;//左边界
    private int right;//右边界
    private int alpha;//透明度
    private AudioManager audioManager;//音频管理
    private int currentVolume;//当前音量
    private int maxVolume;//最大音量
    private boolean isAdjustVolume;//正在调整音量
    private Handler volumeHandler;
    private Runnable volumeRunnable;
    private Context context;


    public VideoProgressBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        int foregroundColor = Color.WHITE;
        mPaint = new Paint();
        mPaint.setColor(foregroundColor);
        bufferPaint = new Paint();
        bufferPaint.setColor(foregroundColor);
        volumePaint = new Paint();
        volumePaint.setColor(Color.YELLOW);
        isBuffer = true;
        //获取音频管理器
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            //获取当前音量
            currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            //获取最大音量
            maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            Log.e(TAG, "当前音量 " + currentVolume + "  最大音量 " + maxVolume);
        }
        initVolumeHandler();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    /**
     * 初始化音量控制Handler
     * 在调整音量的一定时间（1s)后，将设置音量状态取消
     */
    private void initVolumeHandler() {
        volumeHandler = new Handler();
        volumeRunnable = new Runnable() {
            @Override
            public void run() {
                isAdjustVolume = false;
                postInvalidate();
            }
        };
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRect = new Rect(0, getHeight() / 2, getWidth(), getHeight() / 2 + 1);
        progressRect = new Rect(0, 0, 0, getHeight());
        volumeRect = new Rect(0, 0, 0, getHeight());
        alpha = 255;
        changePx = 45;
        left = getWidth() / 2;
        right = getWidth() / 2;
        bufferRect = new Rect(left, 0, right, getHeight());
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画底线
        canvas.drawRect(mRect, mPaint);
        if (isAdjustVolume) {
            //如果正在调整音量，画音量区域，并直接跳出，否则画缓存或者进度
            drawVolume(canvas);
            return;
        }
        if (isBuffer) {
            bufferPaint.setAlpha(alpha);
            canvas.drawRect(bufferRect, bufferPaint);
            setBufferParams();
        } else {
            //是否显示进度
            if (isShowProgress) {
                canvas.drawRect(progressRect, mPaint);
            }
        }
    }

    /**
     * 绘制音量
     */
    private void drawVolume(Canvas canvas) {
        float volumeLength = getWidth() / maxVolume * currentVolume;
        volumeRect.right = (int) volumeLength;
        canvas.drawRect(volumeRect, volumePaint);
        if (volumeHandler != null) {
            volumeHandler.removeCallbacks(volumeRunnable);
            volumeHandler.postDelayed(volumeRunnable, 1000);
        }
    }


    /**
     * 设置缓冲参数
     */
    private void setBufferParams() {
        if (bufferRect.left <= left && bufferRect.left > 0) {
            alpha = 255;
            bufferRect.left -= changePx;
            bufferRect.right += changePx;
        } else {
            if (alpha > 20) {
                alpha -= 10;
            } else {
                bufferRect.left = left;
                bufferRect.right = right;
            }
        }
        postInvalidate();
    }

    /**
     * 设置显示进度条
     * @param isShowProgress 是否显示进度
     */
    public void setShowProgress(boolean isShowProgress){
        this.isShowProgress = isShowProgress;
    }

    /**
     * 设置时长
     */
    public void setDuration(long duration) {
        this.duration = duration;
    }

    public long getDuration() {
        return this.duration;
    }

    /**
     * 设置进度
     */
    public void setShowProgress(long showProgress) {
        if (duration == 0) {
            //如果总长度为0，不显示进度
            isShowProgress = false;
        }
        this.progress = showProgress;
        isBuffer = showProgress == 0;
        if (!isBuffer) {
            setProgressParams();
        }
        postInvalidate();
    }

    /**
     * 获取当前进度
     */
    public long getShowProgress() {
        return this.progress;
    }

    private void setProgressParams() {
        float lengthScale = (float) duration / (float) progress;
        progressRect.right = (int) (getWidth() / lengthScale);
    }


    /**
     * 调整音量
     */
    public void adjustVolume(int adjustType) {
        // 调高音量 AudioManager.ADJUST_RAISE
        // 调低音量 AudioManager.ADJUST_LOWER
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, adjustType, 0);
    }


    /**
     * 监听音量键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //音量加
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            currentVolume++;
            isAdjustVolume = true;
            adjustVolume(AudioManager.ADJUST_RAISE);
            postInvalidate();
            return true;
        }
        //音量减
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            currentVolume--;
            isAdjustVolume = true;
            adjustVolume(AudioManager.ADJUST_LOWER);
            postInvalidate();
            return true;
        }
        //监听返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ((Activity) context).finish();
        }
        return false;
    }
}
